﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfStudy.Command
{
    /// <summary>
    /// FirstForm.xaml 的交互逻辑
    /// </summary>
    public partial class FirstForm : Window
    {
        public FirstForm()
        {
            InitializeComponent();
            InitializeCommand();
        }

        private RoutedCommand clearCmd = new RoutedCommand("Clear", typeof(FirstForm));

        private void InitializeCommand()
        {
            //把命令赋值给命令源（发送者）并指定快捷键
            CommandBtn.Command = clearCmd;
            clearCmd.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt));

            //指定命令目标
            CommandBtn.CommandTarget = textBox;

            //创建命令关联
            CommandBinding cb = new CommandBinding();
            cb.Command = clearCmd;
            cb.CanExecute += new CanExecuteRoutedEventHandler(Cb_CanExecute);
            cb.Executed += new ExecutedRoutedEventHandler(Cb_Executed);

            //把命令关联放在外置控件上。
            textBox.CommandBindings.Add(cb);
        }

        private void Cb_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            textBox.Clear();
            e.Handled =true;
            
        }

        private void Cb_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(textBox.Text))
            {
                e.CanExecute = false;
            }else
            {
                e.CanExecute = true;
            }
            e.Handled = true;
        }
    }
}
